import React, { useRef, useState } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Table, Typography } from 'antd';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

import Filter from '@/components/filter';
import NumberInput from '@/components/number-input';

import { store } from '@/store';

import { usePermission } from '@/auth';
import {
  proDataCostYearList,
  proDataCostYearSave
} from '@/services/bizApi/nianchengbenqingkuangjiekou';

import { tableSource } from './data';
import ImportModal, { ImportRef } from './import';

/** 该模块增删改查对象 */
export type BizObamountct = BIZAPI.ProDataCostYearEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const [filter] = Filter.useForm();
  const [tableData, setTableData] = useState<BizObamountct[]>([]);
  const [selectName, setSelectName] = useState('');
  const [selectIndex, setSelectIndex] = useState(0);
  const importModalRef = useRef<ImportRef>(null);
  const omitArray = ['复合型碳源', '碱', '膜清洗剂', '水费(吨)', '电费(度)']; //被排除不合计的字段
  const table = useAntdTable(
    async () => {
      console.log();
      const res = await proDataCostYearList({
        year: filter.getFieldValue('year')?.format('YYYY') || dayjs().format('YYYY')
      });
      setTableData(res.data!.length > 0 ? (res.data as BizObamountct[]) : tableSource());
      return {
        list: tableData,
        total: res.data?.length || 0
      };
    },
    {
      form: filter
    }
  );

  const generateMonthColumns = (month: number) => {
    const monthKey = `month${month}`;
    const targetKey = `target${month}` as keyof BizObamountct;
    const amountKey = `amount${month}` as keyof BizObamountct;

    return {
      title: `${month}月份`,
      dataIndex: monthKey,
      children: [
        {
          title: '目标量',
          dataIndex: targetKey,
          width: 100,
          render: (value: number, record: BizObamountct, index: number) => (
            <NumberInput
              edit={selectName === record.category && selectIndex === index}
              record={record}
              table={table}
              name={targetKey}
              value={value === 0 ? '' : String(value)}
              onChange={(val) => {
                // const numericValue = val === '' ? 0 : Number(val);
                // const item = tableData.current.find((item) => item.id === record.id);
                // if (item) {
                tableData[index][targetKey] = val as never;
                setTableData([...tableData]);
                // }
              }}
            />
          )
        },
        {
          title: '金额',
          dataIndex: amountKey,
          width: 100,
          render: (value: number, record: BizObamountct, index: number) => (
            <NumberInput
              edit={selectName === record.category && selectIndex === index}
              record={record}
              table={table}
              name={amountKey}
              value={value === 0 ? '' : String(value)}
              onChange={(val) => {
                const numericValue = val === '' ? 0 : Number(val);
                // const item = tableData.current.find((item) => item.id === record.id);
                // if (item) {
                tableData[index][amountKey] = numericValue as never;
                setTableData([...tableData]);
                // }
              }}
            />
          )
        }
      ]
    };
  };

  const defaultColumns: ColumnsType<BizObamountct> = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      fixed: 'left',
      width: 80,
      render: (_, row, index) => index + 1
    },
    {
      title: '类别',
      dataIndex: 'category',
      fixed: 'left',
      width: 200
    },
    ...Array.from({ length: 12 }, (_, index) => generateMonthColumns(index + 1))
  ];

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const { Text } = Typography;

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  importModalRef.current?.open({
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                导入
              </Button>
            )}
            {permission.check() && (
              <Button
                onClick={async () => {
                  console.log(filter);
                  const query = tableData.map((item) => {
                    return {
                      ...item,
                      id: item.id,
                      year: filter.getFieldValue('year')?.format('YYYY') || dayjs().format('YYYY')
                    };
                  });
                  await proDataCostYearSave(query as BIZAPI.ProDataRevenueYearEntity[]);
                  store.app?.message.success('保存成功');

                  setSelectName('');
                  setSelectIndex(-1);
                }}
                type="primary"
              >
                保存
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="year">
          <DatePicker
            picker="year"
            onChange={onSearch}
            placeholder={'请选择年份'}
            format="YYYY"
            value={filter.getFieldValue('year')}
            defaultValue={dayjs()}
          />
        </Filter.Item>

        {/* <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item> */}
      </Filter>
      {/* end 筛选 */}
      {/* 表格 */}
      <Table<BizObamountct>
        size="small"
        columns={defaultColumns as ColumnsType<BizObamountct>}
        onRow={(record, index) => {
          return {
            onClick: (event) => {
              // 点击行的事件处理
              setSelectName(record.category!);
              setSelectIndex(index!);
            }
          };
        }}
        rowKey="id"
        summary={(pageData) => {
          const newPageData = pageData.filter((item) => !omitArray.includes(item.category!));

          let totalTarget1 = 0,
            totalAmount1 = 0,
            totalTarget2 = 0,
            totalAmount2 = 0,
            totalTarget3 = 0,
            totalAmount3 = 0,
            totalTarget4 = 0,
            totalAmount4 = 0,
            totalTarget5 = 0,
            totalAmount5 = 0,
            totalTarget6 = 0,
            totalAmount6 = 0,
            totalTarget7 = 0,
            totalAmount7 = 0,
            totalTarget8 = 0,
            totalAmount8 = 0,
            totalTarget9 = 0,
            totalAmount9 = 0,
            totalTarget10 = 0,
            totalAmount10 = 0,
            totalTarget11 = 0,
            totalAmount11 = 0,
            totalTarget12 = 0,
            totalAmount12 = 0;
          newPageData.forEach(
            ({
              target1,
              amount1,
              target2,
              amount2,
              target3,
              amount3,
              target4,
              amount4,
              target5,
              amount5,
              target6,
              amount6,
              target7,
              amount7,
              target8,
              amount8,
              target9,
              amount9,
              target10,
              amount10,
              target11,
              amount11,
              target12,
              amount12
            }) => {
              totalTarget1 += Number(target1);
              totalAmount1 += Number(amount1);
              totalTarget2 += Number(target2);
              totalAmount2 += Number(amount2);
              totalTarget3 += Number(target3);
              totalAmount3 += Number(amount3);
              totalTarget4 += Number(target4);
              totalAmount4 += Number(amount4);
              totalTarget5 += Number(target5);
              totalAmount5 += Number(amount5);
              totalTarget6 += Number(target6);
              totalAmount6 += Number(amount6);
              totalTarget7 += Number(target7);
              totalAmount7 += Number(amount7);
              totalTarget8 += Number(target8);
              totalAmount8 += Number(amount8);
              totalTarget9 += Number(target9);
              totalAmount9 += Number(amount9);
              totalTarget10 += Number(target10);
              totalAmount10 += Number(amount10);
              totalTarget11 += Number(target11);
              totalAmount11 += Number(amount11);
              totalTarget12 += Number(target12);
              totalAmount12 += Number(amount12);
            }
          );
          return (
            <>
              <Table.Summary.Row>
                <Table.Summary.Cell index={0}></Table.Summary.Cell>
                <Table.Summary.Cell index={1}>
                  <div style={{ textAlign: 'center', fontWeight: 'bold' }}>合计</div>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={2}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget1.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={3}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount1.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={4}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget2.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={5}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount2.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={6}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget3.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={7}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount3.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={8}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget4.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={9}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount4.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={10}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget5.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={11}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount5.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={12}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget6.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={13}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount6.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={14}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget7.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={15}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount7.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={16}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget8.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={17}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount8.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={18}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget9.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={19}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount9.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={20}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget10.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={21}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount10.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={22}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget11.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={23}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount11.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={24}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalTarget12.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={25}>
                  <Text style={{ fontWeight: 'bold' }}>{parseFloat(totalAmount12.toFixed(3))}</Text>
                </Table.Summary.Cell>
              </Table.Summary.Row>
            </>
          );
        }}
        scroll={{
          x: 'max-content'
          // y: 450
        }}
        bordered
        dataSource={tableData}
        // {...table.tableProps}
        pagination={false}
      />
      {/* end表格 */}
      <ImportModal ref={importModalRef} />;
    </>
  );
};

export default Page;
